const formatTime = date => {
  const year = date.getFullYear()
  const month = date.getMonth() + 1
  const day = date.getDate()
  const hour = date.getHours()
  const minute = date.getMinutes()
  const second = date.getSeconds()

  return [year, month, day].map(formatNumber).join('/') + ' ' + [hour, minute, second].map(formatNumber).join(':')
}

const formatNumber = n => {
  n = n.toString()
  return n[1] ? n : '0' + n
}

const wechartLogin = () => {//封装成promise 否则需要登录两次
  return new Promise((resolve,reject)=>{
    wx.login({
       async success (res) {
          if (res.code) {
            //发起网络请求
            const { data } = await request('GET','/wechat/getOpenId',{code:res.code});
            resolve(data);
          } else {
            console.log('登录失败！' + res.errMsg);
          }
        }
      })
  })
}

const request = async (method,url,data) => {
    return new Promise((resolve,reject) => {
        wx.request({
            method,
            header:{
                "authorization":"bearer " + getApp().globalData.userInfo.token || JSON.parse(wx.getStorageSync('userInfo')).token
            },
            url: getApp().baseURL + url,
            data,
            success:(res)=>{
                resolve(res);
            },
            fail:(err)=>{
                reject(err);
            }
        })
    })
}

module.exports = {
  formatTime: formatTime,
  wechartLogin:wechartLogin,
  request:request,
}